package net.zjitc.dao;

import net.zjitc.utils.db.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by Administrator on 2017/12/13.
 */
public class TransationTest {
    //简单事物操作数据库
    public static void main(String[] args) {
    /**
     * 1.获得数据库的连接
     * 2.通过此连接对数据库进行操作
     * 3.关闭连接
     */
        //1.获得数据库的连接，通过数据库连接池获得连接
        Connection connection = null;
        QueryRunner runner = new QueryRunner();
        try {
            connection = C3P0Utils.getConnection();
            //DBUtils工具操作
            connection.setAutoCommit(false);//设置成手动提交
            connection.setSavepoint();
            String sql1 = "update sj set money = money-100 where uname='a'";
            String sql2 = "update sj set money = money+100 where uname='b'";
            runner.update(connection,sql1);
            int count = runner.update(connection,sql2);//返回值可以判断是否更新成功
            if (count==0){
                connection.rollback();//如果sql2的uname名字错误，则直接回滚
            }
            connection.commit();//手动提交
            connection.close();//关闭连接
        } catch (SQLException e) {
            try {
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
    }
}
